const Koa = require('koa')
const Router = require('koa-router')
const staticServer = require('koa-static')
const app = new Koa()
const router = new Router()
const server = require('http').Server(app.callback())
const path = require('path')
const fs = require('fs')

// 静态模板
app.use(staticServer(__dirname+'/build'))

// 广告（假数据模拟）,上线替换真实的数据
var homeAdData = require('./mock/home/ad.js')
router.get('/api/ad', function(ctx, next){
    console.log('广告（假数据模拟）')
    ctx.body = homeAdData
})


router.get("/service-worker.js", (req, res) => {
	ctx.response.type = 'text/javascript'
	ctx.response.body = fs.createReadStream(path.resolve('build/service-worker.js'))
});


// 所有的 koa 路由全部交给 react router
router.get('*',(ctx, next) => {
	ctx.response.type = 'text/html'
	ctx.response.body = fs.createReadStream(path.resolve('build/index.html'))
});

app.use(router.routes())


// 开始服务并生成路由
server.listen(8081,function(){
    console.log('Node app start at port 8081')
})
